package com.briup.prs;

import com.sun.org.apache.regexp.internal.RE;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

public class Step7 extends Configured implements Tool {
    public static  class Step7Mapper  extends Mapper<Text, Text,Text, DoubleWritable>{
        @Override
        protected void map(Text key, Text value, Context context) throws IOException, InterruptedException {
//            类型转换
            double v = Double.parseDouble(value.toString());
            context.write(key,new DoubleWritable(v));
        }
    }

    public static class  Step7Reducer extends Reducer<Text,DoubleWritable,Text,DoubleWritable>{
        private  final  DoubleWritable val=new DoubleWritable();
        @Override
        protected void reduce(Text key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException {
            double sum=0.0;
            for (DoubleWritable value : values) {
                sum+=value.get();
            }
            val.set(sum);
            context.write(key,val);
        }
    }
    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        String in = conf.get("in");
        String out = conf.get("out");
        Job job = Job.getInstance(conf);
        job.setJobName("step7");
        job.setJarByClass(this.getClass());

        job.setInputFormatClass(KeyValueTextInputFormat.class);
        KeyValueTextInputFormat.setInputPaths(job,new Path(in));

        job.setMapperClass(Step7Mapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(DoubleWritable.class);
        job.setReducerClass(Step7Reducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DoubleWritable.class);

        TextOutputFormat.setOutputPath(job,new Path(out));
        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Step7(),args);
    }
}
